package cn.edu.buaa.nlsde.grid.DatabaseManage;

import java.sql.*;

import cn.edu.buaa.nlsde.grid.DatabaseConnect.*;
import cn.edu.buaa.nlsde.grid.Structure.Cluster;

public class ClusterConfigManage
{
	DBConn db=null;
	DBPool dbpool=null;
	Statement stat=null;
	
	public ClusterConfigManage(DBConn db)
	{
		this.db=db;
	}
	public ClusterConfigManage(DBPool dbpool)
	{
		this.dbpool=dbpool;
	}
	
	public Cluster getData(int ClusterID)
	{
		Cluster cluster = new Cluster();
		String sql="select * from Cluster_Config where ClusterID="+ClusterID;
		try 
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			if(rs.next())
			{
				cluster.setName(rs.getString("ClusterName"));
				cluster.setLocalTime(rs.getString("Local_Time"));
				cluster.setOwner(rs.getString("Owner"));
				cluster.setLatlong(rs.getString("Latlong"));
				cluster.setURL(rs.getString("URL"));
				cluster.setClusterDesc(rs.getString("ClusterDesc"));
			}
			rs.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
		
		return cluster;
	}

	public String addRecord(int ClusterID,Cluster cluster)
	{
		String clusterName=cluster.getName();
		String localTime=cluster.getLocalTime();
		String owner=cluster.getOwner();
		String latlong=cluster.getLatlong();
		String url=cluster.getURL();
		String clusterDesc=cluster.getClusterDesc();
		
		String sql="insert into Cluster_Config (ClusterID,ClusterName,Local_Time,Owner,Latlong,URL,ClusterDesc) values ("+ClusterID+",'"+clusterName+"','"+localTime+"','"+owner+"','"+latlong+"','"+url+"','"+clusterDesc+"')";
		System.out.println(sql);
		
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(int ClusterID)
	{
		String sql="delete from Cluster_Config where ClusterID="+ClusterID ;
		try
		{
			stat=dbpool.connect();
			stat.execute(sql);
			return "Success";
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return "Fail";
		}
	}
	
	public String deleteRecord(String ClusterName)
	{
		String sql="delete from Cluster_Config where ClusterName='"+ClusterName+"'";
		try
		{
			stat=dbpool.connect();
			stat.execute(sql);
			return "Success";
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return "Fail";
		}
	}
	
	public void close() throws SQLException
	{
		dbpool.close();
	}
}
